const tool = require('../tools/tool')
const sha256 = require('js-sha256')

const exp = {
    async format(item) {
        item.createdAt_read = tool.formatTimeNew(item.createdAt)
        item.updatedAt_read = tool.formatTimeNew(item.updatedAt)
        return item
    },
    get: {
        async byAccount({ account, withDeleted = false, withFakeData = false }) {
            let re = await tool.dbf().selectWithParams(`select * from users where account = ? ${withDeleted ? `` : ` and isDeleted = 0 `}`, [account])
            if (re.length) {
                return await exp.format(re[0])
            } else {
                if (withFakeData) {
                    return {
                        account: '',
                        username: '账号已注销',
                        isAdmin: 0
                    }
                } else {
                    return undefined
                }
            }
        },
        async byId({ id, withDeleted = false, withFakeData = false }) {
            let re = await tool.dbf().selectWithParams(`select * from users where id = ? ${withDeleted ? `` : ` and isDeleted = 0 `}`, [id])
            if (re.length) {
                return await exp.format(re[0])
            } else {
                if (withFakeData) {
                    return {
                        account: '',
                        username: '账号已注销',
                        isAdmin: 0
                    }
                } else {
                    return undefined
                }
            }
        },
    },
    async update(userId, values) {
        await tool.dbf().updateById('users', userId, values)
    },
    async checkToken(token, needAdmin = false) {
        let re = await tool.parseUserToken({ token })
        let userData = await this.get.byAccount({ acount: re.account, withDeleted: false, withFakeData: false })
        if (!userData) {
            throw '用户不存在'
        }
        if (!userData.token) throw '重新登录'
        if (userData.token != token) {
            throw 'token已失效'
        }
        if (needAdmin && !userData.isAdmin) {
            throw '需要管理员权限'
        }
    },
    setToken: {
        async byAccount(account, token) {
            let userData = await exp.get.byAccount({ account: account, withDeleted: false, withFakeData: false })
            if (!userData) {
                throw '用户不存在'
            }
            await exp.update(userData.id, {
                token
            })
        },
        async byId(userId, token) {
            let userData = await exp.get.byId({ id: userId, withDeleted: false, withFakeData: false })
            if (!userData) {
                throw '用户不存在'
            }
            await exp.update(userData.id, {
                token
            })
        },
    },
    async changePassword(userId, oldPassword, newPassword) {
        let userData = await this.get.byId({ userId, withDeleted: false, withFakeData: false })
        if (!userData) throw '用户不存在'
        if (userData.password != oldPassword) throw '旧密码错误'
        if (!tool.check.checkPassword(newPassword)) throw '密码格式错误'
        await this.update(userId, {
            password: sha256(newPassword)
        })
    },
    async add({
        account,
        password,
        username
    }) {
        let users = await tool.dbf().selectWithParams(`select * from users where account = ?`, [account])
        if (users.length) throw '用户已存在'
        if (!tool.check.checkPassword(password)) throw '密码格式错误'
        return await tool.dbf().insertInto('users', {
            account,
            password: sha256(password),
            username,
            isDeleted: 0,
            token: '',
            isAdmin: 0
        })
    }
}

module.exports = exp